import 'dart:io';

import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/jzx_models.dart';
import 'package:hockey/models/jzx_comment_data.dart';
import 'package:hockey/services/jzx_config.dart';
import 'package:hockey/services/jzx_user.dart';
import 'package:hockey/widgets/sounds_button_single/sounds_button.dart';

import 'controller.dart';
import 'widgets/jzx_voice_bubble.dart';

class JzxPostDetailView extends GetView<JzxPostDetailController> {
  const JzxPostDetailView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      // resizeToAvoidBottomInset: false,
      backgroundColor: const Color(0xFF041506),
      appBar: JzxAAppBar(
        actions: [
          if (JzxUserService.to.uid != controller.uid)
            InkWell(
                onTap: () {
                  controller.showOptions();
                },
                child: Assets.images.icNavMore
                    .image(width: 24)
                    .paddingOnly(right: 20)),
        ],
      ),
      bottomNavigationBar: const _BotMessage(),
      body: SingleChildScrollView(
        child: Column(
          // padding: EdgeInsets.zero,
          children: [
            _BackgroudView(controller: controller),
            _ContentView(controller: controller),
          ],
        ),
      ),
    );
  }
}

class _ContentView extends StatelessWidget {
  const _ContentView({
    super.key,
    required this.controller,
  });

  final JzxPostDetailController controller;

  @override
  Widget build(BuildContext context) {
    return Transform.translate(
      offset: Offset(0, -110.w),
      child: Container(
        // margin: EdgeInsets.only(top: 325.w + kNavigationBarHeight - 110.w),
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 30.w),
        constraints: BoxConstraints(
          minHeight: Get.height - kNavigationBarHeight - 200.w,
        ),
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color(0x00032803),
              Color(0xFF032404),
              Color(0xFF041506),
            ],
            stops: [0, 0.18, 1.0],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: Column(
          children: [
            _ContentHeader(controller: controller),
            _ContentText(controller: controller),
            Obx(
              () => ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: EdgeInsets.only(top: 25.w),
                itemCount:
                    controller.comments.length, // controller.comments.length,
                itemBuilder: (context, index) {
                  // final user = JzxUserService.to.user.value;
                  // final level = JzxUserService.to.userWear.value;
                  final item = controller.comments[index];
                  return _Item(
                      item: item,
                      onLike: () {
                        controller.likeComment(item, index);
                      });
                },
                separatorBuilder: (context, index) => JzxGaps.h12,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _Item extends GetView<JzxPostDetailController> {
  const _Item({
    super.key,
    required this.item,
    required this.onLike,
  });

  final JzxCommentData item;
  final VoidCallback? onLike;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 12, top: 8, bottom: 20, right: 12),
      decoration: BoxDecoration(
          color: const Color(0x26FFFFFF),
          borderRadius: BorderRadius.circular(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              JzxUserFrame(item.avatar, 29.w, level: item.level.levelFormat),
              JzxGaps.w5,
              ConstrainedBox(
                constraints: BoxConstraints(maxWidth: 140.w),
                child: Text(
                  item.nickname,
                  style: myAppColors.text5.font_12.medium,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              JzxGaps.w5,
              Image.asset(
                'assets/images/ic_level${item.level.levelFormat}.png',
                fit: BoxFit.cover,
                height: 15.w,
              ),
            ],
          ),
          JzxGaps.h4,
          item.type == 1
              ? WaveBubble(
                  path: item.content,
                )
              : InkWell(
                  onTap: () {
                    JzxConfigService.to.translate(item.content);
                  },
                  child: Text(
                    item.content,
                    style: myAppColors.white.font_12,
                  ).paddingOnly(left: 29.w + 5),
                ),
          Align(
            alignment: Alignment.topRight,
            child: InkWell(
              onTap: onLike,
              child: item.isLiked
                  ? Assets.images.icListLiked.image(width: 16.w)
                  : Assets.images.icListUnlike.image(width: 16.w),
            ),
          )
        ],
      ),
    );
  }
}

class _BotMessage extends GetView<JzxPostDetailController> {
  const _BotMessage({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return AnimatedPadding(
      duration: Duration.zero,
      padding:
          EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Container(
        color: const Color(0xFF000000),
        padding: EdgeInsets.only(
          left: 20,
          right: 20,
          top: 18,
          bottom:
              17 + (MediaQuery.of(context).viewInsets.bottom > 100 ? 0 : 20),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: Row(
            children: [
              SoundsMessageButton(
                builder: (context, status) =>
                    Assets.images.icMsgVoice.image(width: 32.w),
                onSendSounds: (type, content) {
                  controller.sendComment(content, type: 1);
                },
              ),
              JzxGaps.w12,
              Expanded(
                child: CupertinoTextField(
                  controller: controller.text,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(100),
                  ),
                  placeholder: 'Enter your ideas...',
                  padding: const EdgeInsets.only(
                      left: 20, right: 20, top: 10, bottom: 10),
                  maxLines: null,
                  textInputAction: TextInputAction.send,
                  suffix: InkWell(
                    onTap: () {
                      controller.sendText();
                    },
                    child: Assets.images.icMsgSend
                        .image(width: 32.w)
                        .paddingAll(3),
                  ),
                  onSubmitted: (value) {
                    controller.sendText();
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _ContentText extends StatelessWidget {
  const _ContentText({
    super.key,
    required this.controller,
  });

  final JzxPostDetailController controller;

  @override
  Widget build(BuildContext context) {
    final item = controller.item.value;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        JzxGaps.h12,
        Text(
          item.title,
          style: Colors.white.font_24.copyWith(
            height: 1.7,
          ),
        ),
        JzxGaps.h4,
        Text(
          item.content,
          style: const Color(0x80FFFFFF).font_14.copyWith(
                height: 1.7,
              ),
        ),
        JzxGaps.h8,
        Row(
          children: [
            Assets.images.icTanslate.image(width: 14.w),
            JzxGaps.w6,
            Text('Translate', style: Colors.white.font_12),
          ],
        )
      ],
    );
  }
}

class _ContentHeader extends StatelessWidget {
  const _ContentHeader({
    super.key,
    required this.controller,
  });

  final JzxPostDetailController controller;

  @override
  Widget build(BuildContext context) {
    final user = controller.item.value.user;
    // final item = controller.item.value;
    return Row(
      children: [
        Stack(
          alignment: Alignment.bottomCenter,
          children: [
            JzxUserFrame(user.avatar, 50.w, level: user.level.levelFormat),
            if (JzxUserService.to.uid != controller.uid)
              Positioned(
                child: Obx(
                  () => GradientButton(
                    controller.isFollow.value ? 'Following' : 'Follow +',
                    onPressed: () {
                      controller.followAct();
                    },
                    width: 36.w,
                    height: 14.w,
                    style: GoogleFonts.racingSansOne(
                      fontSize: 6.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              )
          ],
        ),
        JzxGaps.w5,
        ConstrainedBox(
          constraints: BoxConstraints(maxWidth: 140.w),
          child: Text(
            user.nickname,
            style: myAppColors.white.font_20.medium,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        JzxGaps.w5,
        Image.asset(
          'assets/images/ic_level${user.level.levelFormat}.png',
          fit: BoxFit.cover,
          height: 20.w,
        ),
        JzxGaps.expand,
        Obx(() => InkWell(
              onTap: () {
                controller.likeOrCancel();
              },
              child: controller.item.value.isLiked
                  ? Assets.images.icLike.image(width: 54.w)
                  : Assets.images.icUnlike.image(width: 54.w),
            )),
      ],
    );
  }
}

class _BackgroudView extends StatelessWidget {
  const _BackgroudView({
    super.key,
    required this.controller,
  });

  final JzxPostDetailController controller;

  @override
  Widget build(BuildContext context) {
    final item = controller.item.value;
    return SizedBox(
      height: 325.w + kNavigationBarHeight,
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          Swiper(
            loop: false,
            itemCount: item.images.length,
            itemBuilder: (context, index) {
              final image = item.images[index];

              return Container(
                color: Colors.red,
                child: item.author == JzxUserService.to.author
                    ? Image.file(File(image), fit: BoxFit.cover)
                    : Image.asset(image, fit: BoxFit.cover),
              );
            },
            onIndexChanged: (value) {
              controller.swiperCur.value = value;
            },
          ),
          Positioned(
            bottom: 80.w,
            child: Obx(() => Wrap(
                  spacing: 4,
                  children: [
                    ...List.generate(item.images.length, (index) {
                      final active = index == controller.swiperCur.value;
                      return Container(
                        decoration: BoxDecoration(
                          color: active
                              ? const Color(0xFF4DEDB0)
                              : const Color(0x334DEDB0),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        width: active ? 20 : 6,
                        height: 6,
                      );
                    }),
                  ],
                )),
          )
        ],
      ),
    );
  }
}
